package com.czxy.filter;

import com.czxy.domain.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 此类是判断用户是否登录的,能否查看其他页面
 */
@WebFilter(urlPatterns = {"/UserLoginServlet", "*.jsp","*.html","/DownLoadS"})
public class ViewFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        //获取访问ip
        String remoteAddr = httpServletRequest.getRemoteAddr();
        //登录页面和注册页面直接放行和对应的方法直接放行  注册成功页面放行
        String servletPath = httpServletRequest.getServletPath();

        /**
         * 后台放行给其他的filter处理
         */
        if (servletPath.indexOf("admin")!=-1){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        /**
         * 临时
         */
        if (servletPath.endsWith("login.html") || servletPath.endsWith("register.html") || servletPath.startsWith("/UserLoginServlet")||servletPath.endsWith("registerSuccess.jsp")) {
            //放行
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
//        //登录方法放行
//        String method = httpServletRequest.getParameter("method");
//        if ("UserLoginServlet".equals(method)){
//            //放行
//            filterChain.doFilter(servletRequest,servletResponse);
//            return;
//        }

        //判断session域中是否有user
        User loginUser = (User) httpServletRequest.getSession().getAttribute("loginUser");
        if (loginUser != null) {
            //用户登录 放行(暂时 用户权限还未判断)
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        } else {
            //用户未登录 跳转到登录页面
            httpServletResponse.sendRedirect("/pages/login.html");
            return;
        }

    }

    @Override
    public void destroy() {

    }
}
